<template>
  <div>
    <div>
      <div id="container" class="btn1"></div>

      <div class="input-card">
        <h4>轨迹回放控制</h4>
        <div class="input-item">
           <el-button type="primary" size="mini" plain @click="startAnimation()">开始动画</el-button>
           <el-button type="primary" size="mini" plain @click="pauseAnimation()">暂停动画</el-button>
          <!-- <input type="button" class="btn" value="开始动画" id="start" @click="startAnimation()" />
          <input type="button" class="btn" value="暂停动画" id="pause" @click="pauseAnimation()" /> -->
        </div>
        <div class="input-item">
          <el-button type="primary" size="mini" plain @click="resumeAnimation()">继续动画</el-button>
           <el-button type="primary" size="mini" plain @click="stopAnimation()">停止动画</el-button>
          <!-- <input type="button" class="btn" value="继续动画" id="resume" @click="resumeAnimation()" />
          <input type="button" class="btn" value="停止动画" id="stop" @click="stopAnimation()" /> -->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import AMap from "AMap";
//引入最近距离算法
import { navigationResult } from "./functions.js";
//我的位置
import m3 from "./images/m3.png";
export default {
  data() {
    return {
      //经过的坐标点
      approachArr: [],
      //路径
      marker: [
        // [116.739007, 36.488675],
        // [116.883476, 36.576282],
      ],
      lineArr: [
        // [116.739007, 36.488675],
        // [116.883476, 36.576282],
      ],
      title: "", //定位成功
      longitude: undefined, //当前经度
      latitude: undefined, //当前纬度
      parseRouteToPath(route) {
        var path = [];

        for (var i = 0, l = route.steps.length; i < l; i++) {
          var step = route.steps[i];

          for (var j = 0, n = step.path.length; j < n; j++) {
            path.push(step.path[j]);
          }
        }

        return path;
      },
    };
  },
  async mounted() {
    //获取搜索时保存的坐标点值
    await this.getSessionFun();
    await this.longitudeAndLatitude();
    //历史轨迹回放
    await this.lHistoryM();
  },
  methods: {
    //获得当前经纬度
    longitudeAndLatitude() {},
    //历史轨迹-轨迹回放
    async loadingHistoryMap() {
      //获取搜索时保存的坐标点值
      await this.getSessionFun();
      await this.longitudeAndLatitude();
      //历史轨迹回放
      await this.lHistoryM();
    },
    async lHistoryM() {
      let that = this;
      await this.getSessionFun();
      var map =  new AMap.Map("container", {
        resizeEnable: true,
        center: [
          sessionStorage.getItem("longitude") * 1,
          sessionStorage.getItem("latitude") * 1,
        ],
        zoom: 16,
      });
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 10000, //超过10秒后停止定位，默认：5s
        position: "RB", //定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
      });
      geolocation.getCurrentPosition(async function (status, result) {
        if (status == "complete") {
         await onComplete(result);
        } else {
          await onError(result);
        }
      });
      //解析定位结果
      function onComplete(data) {
        that.title = "定位成功";
        that.longitude = data.position.lng;
        that.latitude = data.position.lat;
        console.log("--------456--------");
        console.log(that.longitude, that.latitude);
      }
      this.marker = new AMap.Marker({
        map: map,
        position: [
          sessionStorage.getItem("longitude") * 1,
          sessionStorage.getItem("latitude") * 1,
        ],
        icon: m3,
        offset: new AMap.Pixel(-30, -30),
        autoRotation: true,
        angle: 90,
      });
      // 绘制轨迹
      var polyline = new AMap.Polyline({
        map: map,
        path: this.lineArr,
        showDir: true,
        strokeColor: "#0B9AC3", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6, //线宽
        // strokeStyle: "solid"  //线样式
      });

      var passedPolyline = new AMap.Polyline({
        map: map,
        // path: lineArr,
        strokeColor: "#0B9AC3", //线颜色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6, //线宽
        // strokeStyle: "solid"  //线样式
      });

      this.marker.on("moving", function (e) {
        passedPolyline.setPath(e.passedPath);
      });

      map.setFitView();
    },
    //操作面板
    startAnimation() {
      console.log(this.marker);
      this.marker.moveAlong(this.lineArr, 200);
    },

    pauseAnimation() {
      this.marker.pauseMove();
    },

    resumeAnimation() {
      this.marker.resumeMove();
    },

    stopAnimation() {
      this.marker.stopMove();
    },
    //获取搜索时保存的坐标点值
    async getSessionFun() {
      //获取搜索时保存的坐标点值
      let saveLocation = JSON.parse(sessionStorage.getItem("copyPath"))['length']
        ? JSON.parse(sessionStorage.getItem("copyPath"))
        : [];
      this.approachArr = [];
      this.marker=[];
      this.lineArr=[];
      //获取自己的经纬度

      let minelocation = {
        bookName: "我的位置",
        jingDu: sessionStorage.getItem("longitude") * 1,
        weiDu: sessionStorage.getItem("latitude") * 1,
      };
     await saveLocation.unshift(minelocation);
      for (let i = 0; i < saveLocation.length; i++) {
        if (saveLocation[i]["jingDu"] && saveLocation[i]["weiDu"]) {
          let arr = [
            saveLocation[i]["jingDu"] * 1,
            saveLocation[i]["weiDu"] * 1,
          ];
          this.approachArr.push(arr);
        }
      }
      this.lineArr = JSON.parse(JSON.stringify(this.marker));
      let that = this;
      //行驶路线
      let driveArr = [];
      async function cod() {
        for (let o = 0; o < that.approachArr.length; o++) {
          if (o < that.approachArr.length - 1) {
            let start = [that.approachArr[o][0], that.approachArr[o][1]];
            let ends = [that.approachArr[o + 1][0], that.approachArr[o + 1][1]];
            let rend = await navigationResult(start, ends);
            driveArr.push(rend);
          }
        }
      }
      await cod(this.approachArr);
      //把沿途的点加在this.marker和this.lineArr里面

      //遍历出途径点
      console.log("^^^^^^^^^^^^^^^^^^^^^");
      let tujing = [];
      async function Qr() {
        console.log(driveArr);
        for (let p = 0; p < driveArr.length; p++) {
          for (let q = 0; q < driveArr[p].steps.length; q++) {
            //console.log(driveArr[p].steps)
            for (let s = 0; s < driveArr[p].steps[q].path.length; s++) {
              let ar = [
                driveArr[p].steps[q].path[s]["lng"],
                driveArr[p].steps[q].path[s]["lat"],
              ];
              //console.log(ar);
              tujing.push(ar);
              that.marker = that.lineArr = tujing;
            }
          }
        }
      }
      await Qr(driveArr);
    },
  },
};
</script>
<style scoped>
#container {
  height: 470px;
}
.input-card {
  position: fixed;
  bottom: 15px;
  right: 15px;
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 5px;
  margin-left: 3px;
  width: 200px;
  height: 150px;
  border-width: 0;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: fixed;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 7px 12px;
}
.input-item {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
  height: 30px;
}
</style>